import json

import requests
from loguru import logger

from utils import configs


class RiskAPI:
    @staticmethod
    def get_x5sec(risk_url, account_cookies):
        api_url = configs.SLIDER_API_URL
        # cookie转键值对
        cookies = {}
        # 如果account_cookies是字典直接使用，如果是cookie字符串转字典
        if isinstance(account_cookies, str):
            try:
                for cookie in account_cookies.split('; '):
                    if '=' in cookie:
                        name, value = cookie.split('=', 1)
                        cookies[name] = value
            except Exception as e:
                logger.error(f"解析cookie失败: {e}")
                return {
                    "success": False,
                    "msg": f"解析cookie失败: {e}",
                    "x5sec": None,
                    "raw_response": None
                }
        else:
            cookies = account_cookies

        payload = {
            'parm_url': risk_url,
            'cookie': cookies,
            'key': configs.SLIDER_API_KEY
        }

        logger.info(json.dumps(payload))
        try:
            resp = requests.post(api_url, json=payload, timeout=30)
            
            try:
                raw_response = resp.json()
            except:
                # raw_response = {"text": resp.text, "status_code": resp.status_code}
                return {
                    "success": False,
                    "msg": f"风控接口HTTP错误: {resp}",
                    "x5sec": None,
                    "raw_response": resp
                }
            
            if resp.status_code != 200:
                logger.error(f"风控接口请求失败: HTTP {resp.status_code}")

                return {
                    "success": False,
                    "msg": f"风控接口HTTP错误: {resp.status_code}",
                    "x5sec": None,
                    "raw_response": raw_response
                }

            # {code, msg, data: {code, success}, x5sec, success => code == 200 && x5sec存在}
            code = raw_response.get("code", 0)
            msg = raw_response.get("msg", "")
            x5sec = raw_response.get("x5sec")
            
            # success = code == 200 && x5sec存在
            success = (code == 200) and bool(x5sec)
            
            if success:
                logger.success(f"✅ 风控接口请求成功，x5sec: {x5sec[:20] if x5sec else 'None'}...")
                return {
                    "success": True,
                    "msg": "风控验证成功",
                    "x5sec": x5sec,
                    "raw_response": raw_response
                }
            else:
                error_msg = msg or f"风控接口返回失败: code={code}, x5sec={'存在' if x5sec else '不存在'}"
                logger.error(f"❌ {error_msg}")
                return {
                    "success": False,
                    "msg": error_msg,
                    "x5sec": None,
                    "raw_response": raw_response  # 返回完整响应，便于前端调试
                }
        except Exception as e:
            logger.error(f"风控接口请求异常: {e}")
            return {
                "success": False,
                "msg": f"风控接口请求异常: {str(e)}",
                "x5sec": None,
                "raw_response": None
            }
